<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>日历</title>
    <style>
        table {
            margin: 10px;
            text-align: center;
        }
    </style>
</head>

<body>
    <input type="month">
    <input type="submit" value="确定">
    <table border="2" id="calendar" cellspacing='0'>
        <tr>
            <th>周日</th>
            <th>周一</th>
            <th>周二</th>
            <th>周三</th>
            <th>周四</th>
            <th>周五</th>
            <th>周六</th>
        </tr>
    </table>
    <script>
        var month = document.querySelector('input[type=month]');
        var subBtn = document.querySelector('input[type=submit]');
        var calendar = document.getElementById('calendar');
        // console.log(calendar);


        subBtn.onclick = function () {
            calendar.innerHTML = '<tr>\
                                    <th>周日</th>\
                                    <th>周一</th>\
                                    <th>周二</th>\
                                    <th>周三</th>\
                                    <th>周四</th>\
                                    <th>周五</th>\
                                    <th>周六</th>\
                                </tr> ';
            if (month.value == '') {
                alert("请输入年月！")
            } else {
                var y = month.value.substr(0, 4);
                var m = month.value.substr(5, 2);
            }
            //获得每月的天数
            var days = new Date(y, m, 0).getDate();
            // console.log(days);
            //获得1号是星期几
            var current = new Date(y, m - 1, 1);
            console.log(current);
            var weekOne = current.getDay();
            // weekOne = weekOne == 0 ? 7 : weekOne;
            console.log(weekOne);
            var numRow = Math.ceil((days + weekOne) / 7);
            // console.log(numRow)

            var num = 0;
            for (let i = 0; i < numRow; i++) {
                var tr = document.createElement('tr');
                calendar.appendChild(tr);
                for (let j = 0; j < 7; j++) {
                    var td = document.createElement('td');
                    tr.appendChild(td);
                    num++;
                    if (num <= weekOne || (num - weekOne) > days) {
                        td.innerHTML = "";
                    } else {
                        td.innerHTML = num - weekOne;
                    }
                }
            }
        }




    </script>
</body>

</html>